package com.jsptpd.smartauth.common.util;

import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

public class PageUtil<T> {
    private int totalRecord;// 总记录数
    private int totalPage;// 总页数

    private int pageRecord = 10;// 每页记录数
    private int currentPage;// 当前页码

    private int beginIndex;//起始记录下标
    private int endIndex;//截止记录下标
    private List<T> resultList;

    public PageUtil(int totalRow, int pageNo) {
        this.totalRecord = totalRow;
        this.currentPage = pageNo;
        calculate();
    }

    public PageUtil(int totalRow, Map formData) {
        String pageNum = (String) formData.get("pageNum");
        if (!StringUtils.isEmpty(pageNum)) {
            Integer page = Integer.valueOf(pageNum);
//            if (page != null) page++;
            Integer rows = CommonUtil.String2Integer((String) formData.get("pageSize"));
            if (page != null && rows != null) {
                this.totalRecord = totalRow;
                this.currentPage = page;
                this.pageRecord = rows;
            }
            calculate();
        }

    }

    public PageUtil(int totalRow, int pageNo, int pageSize) {
        this.totalRecord = totalRow;
        if (pageNo > 0) this.currentPage = pageNo;
        if (pageSize > 0) this.pageRecord = pageSize;
        calculate();
    }

    private void calculate() {
        totalPage = totalRecord / pageRecord + ((totalRecord % pageRecord) > 0 ? 1 : 0);

        if (currentPage > totalPage) {
            currentPage = totalPage;
        } else if (currentPage < 1) {
            currentPage = 1;
        }

        beginIndex = (currentPage - 1) * pageRecord;
        if (beginIndex < 0) beginIndex = 0;
        endIndex = beginIndex + pageRecord;
        if (endIndex > totalRecord) {
            endIndex = totalRecord;
        }
    }

    public int getCurrentPage() {
        return currentPage;
    }

    public int getTotalPage() {
        return totalPage;
    }

    public int getTotalRecord() {
        return totalRecord;
    }

    public int getPageRecord() {
        return pageRecord;
    }

    public int getBeginIndex() {
        return beginIndex;
    }

    public int getEndIndex() {
        return endIndex;
    }

    public List<T> getResultList() {
        return resultList;
    }

    public void setResultList(List<T> resultList) {
        this.resultList = resultList;
    }

}
